﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using PloobsEngine;

namespace Etapa1.ModelDescription.ModelSamples
{
    public class GridModel
    {
        public GridModel(int myWidth, int myHeight)
        {
            VertexPositionNormalTexture[] myVertices = new VertexPositionNormalTexture[myWidth * myHeight];

            for (int x = 0; x < myWidth; x++)
                for (int y = 0; y < myHeight; y++)
                {
                    myVertices[x + y * myWidth].Position = new Vector3(x, 0, y);
                    myVertices[x + y * myWidth].Normal = new Vector3(0, 1, 0);
                    myVertices[x + y * myWidth].TextureCoordinate.X = (float)x / 30.0f;
                    myVertices[x + y * myWidth].TextureCoordinate.Y = (float)y / 30.0f;
                }

            vertexBuffer = new VertexBuffer(EngineStuff.GraphicsDevice, VertexPositionNormalTexture.SizeInBytes * myWidth * myHeight, BufferUsage.WriteOnly);
            vertexBuffer.SetData(myVertices);

            short[] terrainIndices = new short[(myWidth - 1) * (myHeight - 1) * 6];
            for (short x = 0; x < myWidth - 1; x++)
            {
                for (short y = 0; y < myHeight - 1; y++)
                {
                    terrainIndices[(x + y * (myWidth - 1)) * 6] = (short)(x + y * myWidth); 
                    terrainIndices[(x + y * (myWidth - 1)) * 6 + 1] = (short)((x + 1) + y * myWidth);
                    terrainIndices[(x + y * (myWidth - 1)) * 6 + 2] = (short)((x + 1) + (y + 1) * myWidth);

                    terrainIndices[(x + y * (myWidth - 1)) * 6 + 3] = (short)(x + (y + 1) * myWidth);
                    terrainIndices[(x + y * (myWidth - 1)) * 6 + 4] = (short)(x + y * myWidth);
                    terrainIndices[(x + y * (myWidth - 1)) * 6 + 5] = (short)((x + 1) + (y + 1) * myWidth);
                }
            }

            indexBuffer = new IndexBuffer(EngineStuff.GraphicsDevice, typeof(short), (myWidth - 1) * (myHeight - 1) * 6, BufferUsage.WriteOnly);
            indexBuffer.SetData(terrainIndices);

            vertexDeclaration = new VertexDeclaration(EngineStuff.GraphicsDevice, VertexPositionNormalTexture.VertexElements);

            primitiveCount = terrainIndices.Count() / 3;
            vertexCount = myWidth * myHeight;
        }

        public VertexBuffer vertexBuffer;
        public IndexBuffer indexBuffer;
        public VertexDeclaration vertexDeclaration;
        public int vertexCount;
        public int primitiveCount;

    }
}
